<!-- 生产溯源信息 -->
<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <template v-slot:table>
      <div class="baseInfoList flex" v-loading="loading">
        <div class="baseInfo flex" v-for="fishData, index in  tableData " :key="index"
          @click="jumpFishInfo(fishData); setTime()">
          <div class="fishImg">
            <div class="fishImgBox">
              <img v-show="fishSpeciesObj[fishData.fishVarietyId]" :src="getImageList(fishSpeciesObj[fishData.fishVarietyId])" alt="">
            </div>
          </div>
          <div class="info" style="padding-left: 30px;">
            <div>批次编号：<span style="color: #999999;">{{ batchObj[fishData.batchId] }}</span></div>
            <div>养殖设施：<span style="color: #999999;">{{ fishData.fishPondName }}</span></div>
            <div>养殖品种：<span style="color: #999999;">{{ fishData.fishVarietyName }}</span></div>
            <div>养殖主体：<span style="color: #999999;">{{ homeBaseName }}</span></div>
            <div>主体地址：<span style="color: #999999;">{{ address }}</span></div>
          </div>
          <div class="QRCode">
            <div class="imgBox">
              <Qrcode v-if="showTable" :apkUrl="getApkUrl(fishData)">
              </Qrcode>
            </div>
            <div>扫码溯源</div>
          </div>
        </div>
      </div>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="changeCurrentPage" :page="currentPage" :size="pageSize" :total="totalSize">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog title="溯源信息" :visible.sync="dialogVisible" width="90%" :before-close="handleClose">
        <div class="TraceabilityMsgParticulars">
          <TraceabilityMsgParticulars v-if="showTable" :batchParticularsInfo="batchInfo" />
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">关 闭</el-button>
        </span>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import SearchForm from '@/components-production-management/SearchForm';
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import Qrcode from "@/components/qrcode";
import TraceabilityMsgParticulars from "@/components/traceabilityMsgParticulars";  // 
import subjectInfoApi from "@/api/traceability/basicsInfo/subjectInfo";            // 主体信息
//品种
import fishVarietyApi from "@/api/basic-info-manage/fishVariety"
//批次
import batchManagement from '@/api/production-management/batch-management.js';
//鱼塘
import fishPondApi from "@/api/basic-info-manage/fishPond";

import fishSpeciesImgApi from "@/api/traceability/basicsInfo/fishSpeciesImg";
import pondStockingManagement from '@/api/production-management/pond-stocking-management.js';
import FishVarietyApi from "@/api/basic-info-manage/fishVariety"
import BatchMangeApi from "@/api/batch-mange";
import { mymixin } from "@/utils/mixin";
import { mapGetters } from "vuex";

import DocumentApi from "@/api/document";
import { blobToBase64 } from "@/utils/convert";
export default {
  name: "StaffManage",
  components: {
    MainSlot,
    SearchForm,
    Pagination,
    BaseMainSlot,
    Qrcode,
    TraceabilityMsgParticulars
  },
  mixins: [mymixin],
  data() {
    return {
      unfoldFlag: false,
      loading: false,
      address: '', // 主体地址
      dialogVisible: false,
      homeBaseName: sessionStorage.getItem('homeBaseName'),
      homeBaseId: sessionStorage.getItem('homeBaseId'),
      activeName: '',
      currentPage: 1,
      totalSize: 1,
      pageSize: 4,
      // 查询条件
      searchObj: {},
      options: [],
      fishVarietyList: [],
      fishSpeciesImg: [],
      fishSpeciesObj: {},
      batchList: [],
      allbatchList: [],
      batchInfo: {},
      batchObj: {},
      batchCodeObj:{},
      showTable: true,
      formItemList: [
        {
          label: '养殖鱼塘',
          type: 'select',
          selectOptions: [],
          param: 'fishPondId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '养殖批次',
          type: 'select',
          selectOptions: [],
          param: 'batchId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '称重品种',
          type: 'select',
          selectOptions: [],
          param: 'fishVarietyId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }
      ],
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {},
  created() {
  },
  mounted() {
    this.queryPageList()
    this.queryAllList()
    this.queryByHomeBaseId() // 主体信息
    this.initData();
  },
  methods: {
    getImageList(id) {
      console.log(id)
      return `${this.$baseurl.fileServiceUrl}base/files/preview?fileId=${id}`
    },
    getApkUrl(row) {
      let params = {
        batchId: row.batchId,
        batchName: row.batchName,
        fishPondId: row.fishPondId,
        batchCode: row.batchCode,
        fishVarietyId: row.fishVarietyId,
        varietyName: row.varietyName,
        homeBaseId: this.homeBaseId,
        traceSourceFlag: false
      }
      let url = 'http://fishery.ssagroup.cn:8080/h5/#/'
      let data = '';
      for (let key in params) {
        data += `&${key}=${params[key]}`
      }
      return `${url}?${data}`
    },
    //初始化数据
    async initData() {
      let { data: fishPondList } = await fishPondApi.queryByCondition({ bindBatch: true });//查询鱼塘列表 //bindBatch:true 查询绑定了批次的鱼塘
      let { data: batchList } = await batchManagement.queryByCondition({ unCompleteBatch: true });//查询批次列表
      let { data: allbatchList } = await batchManagement.queryByCondition();//查询批次列表
      let { data: fishVarietyList } = await fishVarietyApi.queryByCondition();//查询品种
      let { data: fishSpeciesImg } = await fishSpeciesImgApi.queryByCondition();
      fishSpeciesImg.forEach(item => {
        this.fishSpeciesObj[item.varietyId] = item.pictureId
      })
      this.fishPondList = fishPondList || [];
      this.batchList = batchList || [];
      this.allbatchList = allbatchList || [];
      this.fishSpeciesImg = fishSpeciesImg || [];
      allbatchList.forEach(item => {
        this.batchObj[item.batchId] = item.batchName;
        this.batchCodeObj[item.batchId] = item.batchCode
      })
      this.fishVarietyList = fishVarietyList || [];
      this.setFormOptions();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('fishPondId') !== -1) {
          let selectOptions = this.fishPondList.map(data => {
            return {
              text: data.pondName, value: data.fishPondId
            }
          })
          item.defaultSelect = this.searchObj[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('fishVarietyId') !== -1) {
          let selectOptions = this.fishVarietyList.map(data => {
            return {
              text: data.varietyName, value: data.fishVarietyId
            }
          })
          item.defaultSelect = this.searchObj[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('batchId') !== -1) {
          let selectOptions = this.allbatchList.map(data => {
            return {
              text: data.batchName, value: data.batchId
            }
          })
          item.defaultSelect = this.searchObj[item.param];
          item.selectOptions = selectOptions;
        };

      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    //搜索
    search(data) {
      this.page = 1;
      this.searchObj = {
        ...this.searchObj,
        ...data,
      };
      this.queryPageList();
    },
    setTime() {
      this.showTable = false
      setTimeout(() => {
        this.showTable = true
      }, 10)
    },
    handleClose(done) {
      this.batchInfo = {}
      done()
    },
    jumpFishInfo(data) {
      this.batchInfo = {
        batchId: data.batchId,
        batchCode: this.batchCodeObj[data.batchId],
        fishPondId: data.fishPondId,
        fishVarietyId: data.fishVarietyId
      }
      console.log(this.batchInfo)
      this.dialogVisible = true
    },
    handleChange() {
      this.activeName ? this.activeName = '1' : this.activeName = ''
    },
    queryAllList() {
      FishVarietyApi.queryByCondition().then(res => {
        this.fishVarietyList = res.data
      })
      BatchMangeApi.queryByCondition({
        status: "COMPLETED"
      }).then(res => {
        this.batchList = res.data;
      })
    },

    async fileDownload(fileId) {
      let res = fileId && await DocumentApi.fileDownload({ fileId })
      console.log(res, '---')
      let img = await blobToBase64(res.data)
      return img
    },
    //查询溯源信息列表
    queryPageList() {
      let params = {
        page: this.currentPage,
        size: 4,
        entity: {
          ...this.searchObj
        }
      };
      this.loading = true;
      pondStockingManagement.batchPondInfoPageList(params).then(res => {
        this.loading = false;
        this.setTime()
        if (res.success) {
          res.data.content.forEach(async (item) => {
            if (item.pictureId) {
              item['pictureImg'] = this.$baseurl.fileServiceUrl + 'base/files/preview?fileId=' + item.pictureId
            } else {
              item['pictureImg'] = require("@/assets/fish.jpg")
            }
          })
          this.totalSize = res.data.totalElements;
          this.tableData = res.data.content;
        }
        this.routerParams = {}
      }).catch(err => {
        console.log(err)
        this.loading = false;
      });
    },
    // 获取主体信息
    queryByHomeBaseId() {
      subjectInfoApi.queryByHomeBaseId({ homeBaseId: sessionStorage.getItem('homeBaseId') }).then(res => {
        if (res && res.data) {
          this.address = res.data.address
        }
      })
    },
    changeCurrentPage(e) {
      this.currentPage = e
      this.queryPageList()
    }
  },
};
</script>

<style lang="scss" scoped>
.flex {
  display: flex;
  justify-content: space-between;
  flex-flow: row wrap
}

.baseInfoList {
  height: 100%;
  width: 100%;
  padding: 20px 15px;

  .baseInfo {
    width: calc(50% - 20px);
    height: 240px;
    box-sizing: border-box;
    margin: 10px 10px;
    background: #ffffff;
    align-items: center;
    justify-content: flex-start;
    position: relative;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0px 0px 10px 0px #49c8ff;
    cursor: pointer;

    .fishImg {
      width: 260px;
      height: 100%;
      background: #cecece;
      background-image: url("~@/assets/haibg.png");

      .fishImgBox {
        width: calc(100% - 40px);
        height: calc(100% - 40px);
        margin: 20px;
        border-radius: 8px;
        box-sizing: border-box;
        background: #3333335c;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          box-shadow: 0 0 10px 0 #cecece;
        }
      }
    }

    .info {
      text-align: left;
      color: #333;
      padding: 0 10px;
      font-size: 16px;
      line-height: 30px;
      width: 300px;
    }

    .QRCode {
      position: absolute;
      top: 0;
      right: 30px;
      width: 150px;
      height: 100%;
      text-align: center;
      color: #333;
      font-size: 16px;
      padding: 30px 0;
      background: #d7eaff;

      .imgBox {
        height: calc(130px);
        width: calc(130px);
        margin: 0 auto;
        margin-bottom: 10px;
        padding: 5px;
        background: #ffffff;
        box-sizing: border-box;

        img {
          width: calc(100%);
          height: calc(100%);
        }
      }
    }
  }
}

::v-deep .el-dialog {
  margin-top: 50px !important;
}

.TraceabilityMsgParticulars {
  width: 100%;
  height: calc(100vh - 300px);
  overflow: auto;
}
</style>
